-----------------------------------------------------------------------------------------
-- filename : tile.lua
-- description : tile object
-----------------------------------------------------------------------------------------

-- load needed libraries/scripts
local layer = require "layer"

-- local variables
local tile = {}
local tile_mt = {__index = tile}
-- STATIC
tile.BLANK = 0
tile.DEATH = 1
tile.PLUS1 = 2
tile.MIN1 = 3
tile.HALF = 4
tile.DOUBLE = 5
tile.BARRED = 6
tile.DIRECTION = 7
tile.MOVEMENT1 = 8
tile.JUMP = 9
tile.REROLL = 10
tile.BEAM = 11
tile.REBIRTH = 12

tile.DIR_UP = 2
tile.DIR_DOWN = 3
tile.DIR_LEFT = 1
tile.DIR_RIGHT = 0

-- PRIVIATE FUNCTION

-- PUBLIC FUNCTION

function tile.new(typeTile,xPos,yPos,width,height,direction)
	local newTile = {
		tile_type = typeTile,
		direction = direction or 0,
		image = display.newImageRect( "assets/tile"..typeTile..".png", width, height ),
		animation = nil
	}

	newTile.image:setReferencePoint(display.TopLeftReferencePoint)
	newTile.image.x = xPos
	newTile.image.y = yPos

	newTile.image:setReferencePoint(display.CenterReferencePoint)
	if(newTile.direction == tile.DIR_UP) then
		newTile.image.rotation = 270
	elseif(newTile.direction == tile.DIR_DOWN) then
		newTile.image.rotation = 90
	elseif(newTile.direction == tile.DIR_LEFT) then
		newTile.image.rotation = 180
	end

	layer.insertImage(layer.BOARD,newTile.image)

	return setmetatable(newTile, tile_mt)
end

function tile:playAnim()
	if(self.tile_type == tile.BARRED) then
		local sheetData = {
			width=169,
			height=167,
			numFrames=4,
			sheetContentWidth=169*2,
			sheetContentHeight=167*2
		}

		local mySheet = graphics.newImageSheet("assets/tile_animation/barred_sheet.png",sheetData)
		
		local sequenceData = {
			{
				name = "animation",
				start = 1,
				count = 4,
				time = 1000, -- time in millisecond
				loopCount = 0,
				loopDirection = "forward"
			}
		}

		local animation = display.newSprite(mySheet, sequenceData)
		animation.x = self.image.x
		animation.y = self.image.y

		animation:play()
		self.animation = animation;
		layer.insertImage(layer.DIR,animation)
	elseif (animation ~= nil) then
		self.animation:play()
	end
end

function tile:stopAnim()
	if(self.animation ~= nil and object.isPlaying == true) then
		self.animation:pause()
	end
end

return tile